home *** CD-ROM | disk | FTP | other *** search
/ Workbench Add-On / Workbench Add-On - Volume 1.iso / BBS-Archive / Comm / AmiTCP30b2.lha / src / netlib / set_socket_stdio.c < prev    next >
C/C++ Source or Header  |  1994-05-02  |  2KB  |  81 lines

  1. RCS_ID_C="$Id: set_socket_stdio.c,v 1.2 1994/05/02 19:35:42 jraja Exp $";
  2. /*
  3.  * set_socket_stdio.c - redirect stdio to/from a socket
  4.  *
  5.  * Author: jraja <Jarno.Rajahalme@hut.fi>
  6.  *
  7.  * Copyright © 1994 AmiTCP/IP Group, <amitcp-group@hut.fi>
  8.  *                  Helsinki University of Technology, Finland.
  9.  *                  All rights reserved.
  10.  *
  11.  * Created      :
  12.  * Last modified:
  13.  */
  14.  
  15. /****** net.lib/set_socket_stdio ****************************************
  16.  
  17.     NAME
  18.         set_socket_stdio - redirect stdio to/from a socket
  19.  
  20.     SYNOPSIS
  21.         int set_socket_stdio(int sock);
  22.  
  23.     FUNCTION
  24.         Redirect stdio (stdin, stdout and stderr) to/from socket 'sock'.
  25.         This is done by dup2()'ing 'sock' to the level 1 files underneath
  26.         the stdin, stdout and stderr.
  27.  
  28.     The original 'sock' reference is closed on successful return, so
  29.     the socket descriptor given as argument should not be used after
  30.         this function returns (successfully).
  31.  
  32.     RETURN VALUES
  33.         0 if successful, -1 on error. Global variable 'errno' contains
  34.         the specific error code set by the failing function.
  35.  
  36.     NOTES
  37.         This module pulls in the link library stdio modules.
  38.  
  39.     AUTHOR
  40.         Jarno Rajahalme, the AmiTCP/IP Group <amitcp-group@hut.fi>,
  41.         Helsinki University of Technology, Finland.
  42.  
  43.     SEE ALSO
  44.         dup2()
  45. *****************************************************************************
  46. *
  47. */
  48.  
  49. #include <bsdsocket.h>
  50.  
  51. #include <stdio.h>
  52. #include <stdlib.h>
  53.  
  54. int
  55. set_socket_stdio(int sock)
  56. {
  57.   /*
  58.    * Replace the stdio with the sock
  59.    */
  60.   if (sock >= 0
  61.       && dup2(sock, fileno(stdin)) >= 0
  62.       && dup2(sock, fileno(stdout)) >= 0
  63.       && dup2(sock, fileno(stderr)) >= 0)
  64.     {
  65.       /* 
  66.        * line buffered mode
  67.        */
  68.       setvbuf(stdin, NULL, _IOLBF, 0);
  69.       setvbuf(stdout, NULL, _IOLBF, 0);
  70.       setvbuf(stderr, NULL, _IOLBF, 0);
  71.       /*
  72.        * Close the original reference to the sock if necessary
  73.        */
  74.       if (sock > fileno(stderr))
  75.     CloseSocket(sock);
  76.  
  77.       return 0;
  78.     }
  79.   return -1;
  80. }
  81.